#encoding='utf-8'
import sys
import time
from selenium import webdriver
import requests
import csv
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
driver = webdriver.Chrome(executable_path='C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe')
login = "https://zhtj.youth.cn/zhtj/signin"
driver.get(login)



def getCookie():

    driver.find_element_by_id('loginId').send_keys('这里改成账号')
    driver.find_element_by_id('password').send_keys('这里改成密码')
    yzm = input('请输入验证码 ')
    driver.find_element_by_id('yzm').send_keys(yzm)
    driver.find_element_by_class_name('logo_but').click()
    time.sleep(3)
    cookie = [item["name"] + "=" + item["value"] for item in driver.get_cookies()]
    print(cookie)
    cookiestr = ';'.join(item for item in cookie)
    print(cookiestr)
    final = {}
    for line in cookiestr.split(';'):
        name, value = line.strip().split('=', 1)
        final[name] = value
    return final

def getToken():
    token = input('token')
    return token

def getMemberCountList(cookie, token):
    data = {'currLeagueId': 'Gzrpte3Q',
            'currUserId': 'uDOpcs4Q'}
    headers = {'Accept': 'application/json, text/plain, */*',
                'Referer': 'https://zhtj.youth.cn/zhtj/center/tuanyuantw/memberlist',
                'Sec-Fetch-Mode': 'cors',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
                'X-CSRF-Token': token,
                'zhtj-Lid': 'Gzrpte3Q',
                'zhtj-Uid': 'uDOpcs4Q'}
    url = 'https://zhtj.youth.cn/v1/center/getorgtree/Gzrpte3Q'

    r = requests.post(url = url, data=data, cookies = cookie, headers = headers)
    r.encoding='utf-8'
    json_text = r.json()

    reList = json_text['results']['leagueList']
    final_list = []
    for i in reList:
        final_list.append(i['leagueId'])
    final_list.pop(0)
    return final_list

def getUserId(cookies, token, queryLeagueId):
    page = 1
    headers = {'Accept': 'application/json, text/plain, */*',
               'Referer': 'https://zhtj.youth.cn/zhtj/center/tuanyuantw/memberlist',
               'Sec-Fetch-Mode': 'cors',
               'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
               'X-CSRF-Token': token,
               'zhtj-Lid': 'Gzrpte3Q',
               'zhtj-Uid': 'uDOpcs4Q'}
    data = {'currLeagueId': 'Gzrpte3Q',
            'currUserId': 'uDOpcs4Q',
            'queryLeagueId': queryLeagueId,
            'queryLeagueTypeId': '01TZB',
            'sectionName': 'first',
            'queryRole': 0,
            'orgCate': '',
            'orgName': '',
            'page': page}
    url = 'https://zhtj.youth.cn/v1/center/tuanyuantw/list'
    r = requests.post(url=url, data=data, cookies=cookies, headers=headers)
    r.encoding = 'utf-8'
    js = r.json()
    reList = js['results']['userList']
    final_list = []
    for num in reList:
        final_list.append(num['userId'])
    while js['results']['page']*10 < js['results']['totalNumber']:
        page += 1
        data = {'currLeagueId': 'Gzrpte3Q',
                'currUserId': 'uDOpcs4Q',
                'queryLeagueId': queryLeagueId,
                'queryLeagueTypeId': '01TZB',
                'sectionName': 'first',
                'queryRole': 0,
                'orgCate': '',
                'orgName': '',
                'page': page}
        r = requests.post(url=url, data=data, cookies=cookies, headers=headers)
        r.encoding = 'utf-8'
        js = r.json()
        reList = js['results']['userList']
        for num in reList:
            final_list.append(num['userId'])
    print(final_list, len(final_list))
    return final_list

def getmemberInfo(cookies, token, queryLeagueId, userId):
    data = {'currLeagueId': 'Gzrpte3Q',
            'currUserId': 'uDOpcs4Q',
            'userId': userId,
            'queryLeagueId': queryLeagueId}
    headers = {'Accept': 'application/json, text/plain, */*',
               'Referer': 'https://zhtj.youth.cn/zhtj/center/tuanyuantw/memberlist',
               'Sec-Fetch-Mode': 'cors',
               'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
               'X-CSRF-Token': token,
               'zhtj-Lid': 'Gzrpte3Q',
               'zhtj-Uid': 'uDOpcs4Q'}
    url = 'https://zhtj.youth.cn/v1/center/getmemberInfo'
    r = requests.post(url=url, data=data, cookies=cookies, headers=headers)
    r.encoding = 'utf-8'
    json_text = r.json()
    person = {}
    person['leagueFullName'] = json_text['results']['leagueFullName']
    person['name'] = json_text['results']['name']
    person['gender'] = json_text['results']['gender']
    person['identityCardNo'] = json_text['results']['identityCardNo']
    person['nationalId'] = json_text['results']['nationalId']
    person['politicalId'] = json_text['results']['politicalId']
    person['joinLeagueTime'] = json_text['results']['joinLeagueTime']
    person['mobile'] = json_text['results']['mobile']
    return person


def getcadresInfo(cookies, token, queryLeagueId, userId):
    data = {'currLeagueId': 'Gzrpte3Q',
            'currUserId': 'uDOpcs4Q',
            'userId': userId,
            'queryLeagueId': queryLeagueId}
    headers = {'Accept': 'application/json, text/plain, */*',
               'Referer': 'https://zhtj.youth.cn/zhtj/center/tuanyuantw/memberlist',
               'Sec-Fetch-Mode': 'cors',
               'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
               'X-CSRF-Token': token,
               'zhtj-Lid': 'Gzrpte3Q',
               'zhtj-Uid': 'uDOpcs4Q'}
    url = 'https://zhtj.youth.cn/v1/center/getcadresInfo'
    r = requests.post(url=url, data=data, cookies=cookies, headers=headers)
    r.encoding = 'utf-8'
    json_text = r.json()
    person = {}
    if json_text['retCode'] == 1000:
        person['leagueFullName'] = json_text['results']['leagueFullName']
        person['name'] = json_text['results']['name']
        person['gender'] = json_text['results']['gender']
        person['identityCardNo'] = json_text['results']['identityCardNo']
        person['nationalId'] = json_text['results']['nationalId']
        person['politicalId'] = json_text['results']['politicalId']
        person['joinLeagueTime'] = json_text['results']['joinLeagueTime']
        person['mobile'] = json_text['results']['mobile']
    elif json_text['retCode'] == 6788:
        person = getmemberInfo(cookies, token, queryLeagueId, userId)
    print(person)
    return person


def write(alllist):
    with open('.\\info2.csv', mode='w', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(
            f,
            fieldnames=[
                'leagueFullName',
                'name',
                'gender',
                'identityCardNo',
                'nationalId',
                'politicalId',
                'joinLeagueTime',
                'mobile'])
        writer.writeheader()
        for each in alllist:
            writer.writerow(each)

def main():
    cookies = getCookie()
    token = getToken()
    MemberCountList = getMemberCountList(cookies, token)
    re = []
    for i in MemberCountList:
        UserIdList = getUserId(cookies, token, i)
        for j in UserIdList:
            memberInfoDic = getcadresInfo(cookies, token, i, j)
            re.append(memberInfoDic)
    write(re)

if __name__ == '__main__':
    main()


